layui.define(['layer', 'conf', 'msg', 'utils'], function(exports){
	var $ = layui.jquery;
	var layer = layui.layer;
	var msg = layui.msg;
	var utils = layui.utils;
	var conf = layui.conf;
	
	statusName = conf.response.statusName || "code";
	statusCode = conf.response.statusCode || 0;
	tokenInvalidCode = conf.response.tokenInvalidCode || null;
	tokenName = conf.tokenName || "TOKEN";
	
	
	ajax = {
		get : function(url, data, o = {}){
			return this.req(url, data, $.extend({
				method : "GET",
			},o));
		},
		post : function(url, data, o = {}){
			return this.req(url, data, $.extend({
				method : "POST",
			},o));
		},
		req : function(url, data, o){
			o = $.extend({
				loading : true,
				showTip : true
			}, o)
			delete o.success;
			delete o.error;
			var headers = o.header;
			var headerToken = {};
			headerToken[tokenName] = ajax.getToken();
			delete o.header;
			o.loading && msg.load();
			return $.ajax($.extend({
				url,
				data,
				headers:$.extend(headerToken,conf.requestHeader, headers),
				success: function(resp){
					o.loading && msg.removeLoad();
					msgCallBack = function(isOk){
						isOk ? o.ok && o.ok(resp) : o.fail && o.fail(resp, false);
						o.done && o.done(resp);
					}
					o.doCallBack ? o.doCallback(resp) : ajax.doCallback(resp, o.showTip, msgCallBack);
					
				},
				error: function(e){
					o.loading && msg.removeLoad();
					msg.error("请求错误");
					o.fail && o.fail(e, true);
					
				}
			}, o)).always(function(){
				o.always && o.always();
			});
		},
		
		doCallback : function(resp, showTip, fun){
			resp = typeof(resp) === "string" ? eval('(' + resp + ')') : resp;
			var okShowTip = false, failShowTip = false, loginTimeOutShowTip = false;
			if(typeof(showTip) === 'object'){
				okShowTip = utils.isBlank(showTip.ok) ? true : showTip.ok;
				failShowTip = utils.isBlank(showTip.fail) ? true : showTip.fail;
				loginTimeOutShowTip = utils.isBlank(showTip.loginTimeOut) ? true : showTip.loginTimeOut;
			}else{
				okShowTip = failShowTip = loginTimeOutShowTip = showTip;
			}
			if(tokenInvalidCode && (resp[statusName] === tokenInvalidCode || $.inArray(resp[statusName], tokenInvalidCode) >= 0)){
				loginTimeOutShowTip ? msg.error("登录超时,请重新登录", function(){
					location.href = conf.loginUrl;
				}) : (location.href = conf.loginUrl)
				return false;
			}
			if(resp[statusName] === statusCode){
				okShowTip ? msg.success(resp[conf.response.msgName], function(){
					fun(true)
				}) : fun(true)
				return true;
			}else{
				failShowTip ? msg.error(resp[conf.response.msgName], function(){
					fun(false)
				}) : fun(false);
				return false;
			}
		},
		getToken : function(){
			return layui.data(conf.tableName)[tokenName];
			
		},
		setToken : function(token){
			layui.data(conf.tableName, {
				key : tokenName,
				value : token
			})
		}
		
	}
	
	exports('ajax', ajax);
});